﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;
using SharpShare.Storage.Security;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpMoveRenameRequestHandler : IAfpRequestHandler {
        #region IAfpRequestHandler Members

        public byte CommandCode {
            get { return 23; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort volumeId = requestStream.ReadUInt16();
            uint sourceDirId = requestStream.ReadUInt32();
            uint destDirId = requestStream.ReadUInt32();

            var sourcePath = requestStream.ReadPath().ToList();
            var destPath = requestStream.ReadPath().ToList();
            var newName = requestStream.ReadPath().SingleOrDefault();

            IAfpVolume volume;

            IStorageItem sourceItem = session.FindPath(sourcePath, volumeId, sourceDirId, out volume);
            IStorageContainer destinationContainer = session
                .FindPath(destPath, volumeId, destDirId, out volume)
                .DemandContainer();

            StorageAccessList sourceAccess = sourceItem.GetEffectiveAccess(session);
            StorageAccessList destinationAccess = destinationContainer.GetEffectiveAccess(session);

            sourceAccess.DemandRight(StorageAccessRight.Delete);

            if (sourceItem.Parent != null) {
                sourceItem.Parent.GetEffectiveAccess(session).DemandRight(StorageAccessRight.DeleteChild);
            }

            destinationAccess.DemandRight(StorageAccessRight.AddFiles, StorageAccessRight.AddContainers);

            if (string.IsNullOrEmpty(newName)) {
                newName = sourceItem.Name;
            }

            sourceItem.Move(destinationContainer, newName);

            //try {
            //    sourceItem.DateModified = DateTime.Now;
            //} catch { }

            //if (sourceItem.Parent != null) {
            //    try {
            //        sourceItem.Parent.DateModified = DateTime.Now;
            //    } catch { }
            //}

            //if (destinationContainer.Parent != null) {
            //    try {
            //        destinationContainer.Parent.DateModified = DateTime.Now;
            //    } catch { }
            //}

            return AfpResultCode.FPNoErr;
        }

        #endregion
    }
}
